package com.rcloud.server.sealtalk.service;

import com.rcloud.server.sealtalk.dao.UserDeviceMapper;
import com.rcloud.server.sealtalk.domain.UserDevice;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: xiuwei.nie
 * @Date: 2020/7/6
 * @Description:
 * @Copyright (c) 2020, rongcloud.cn All Rights Reserved
 */
@Service
public class UserDeviceService extends AbstractBaseService<UserDevice, Integer> {

    @Resource
    private UserDeviceMapper mapper;

    @Override
    protected Mapper<UserDevice> getMapper() {
        return mapper;
    }


    /**
     * @param userId
     */
    public void saveOrUpdate(Integer userId, String device) {
        Example example = new Example(UserDevice.class);
        example.createCriteria().andEqualTo("userId", userId)
                .andEqualTo("device", device);

        UserDevice userDevice = mapper.selectOneByExample(example);
        if (userDevice == null) {
            userDevice = new UserDevice();
            userDevice.setUserId(userId);
            userDevice.setDevice(device);
            userDevice.setCreatedAt(new Date());
            userDevice.setUpdatedAt(userDevice.getCreatedAt());
            this.saveSelective(userDevice);
        } else {
            UserDevice newUserDevice = new UserDevice();
            newUserDevice.setId(userDevice.getId());
            newUserDevice.setUpdatedAt(new Date());
            this.updateByPrimaryKeySelective(newUserDevice);
        }
    }


    /**
     * @param currentUserId
     * @return
     */
    public List<UserDevice> getDevicesWithUser(Integer currentUserId) {
        Example example = new Example(UserDevice.class);
        example.createCriteria().andEqualTo("userId", currentUserId);
        return mapper.selectByExample(example);
    }

    /**
     * @return
     */
    public int deleteDevice(Integer userId, String device) {
        Example example = new Example(UserDevice.class);
        example.createCriteria().andEqualTo("userId", userId)
                .andEqualTo("device", device);
        return mapper.deleteByExample(example);
    }

    /**
     * @return
     */
    public UserDevice getDevice(Integer userId, String device) {
        Example example = new Example(UserDevice.class);
        example.createCriteria().andEqualTo("userId", userId)
                .andEqualTo("device", device);
        return mapper.selectOneByExample(example);
    }
}
